package com.kintreda.common.oauth.security.service;

import com.alibaba.fastjson.JSONObject;
import com.kintreda.common.config.constant.RedisConstant;
import com.kintreda.common.config.enums.UserTypeEnum;
import com.kintreda.common.config.redis.RedisUtils;
import com.kintreda.common.mybatis.entity.SysAdmin;
import com.kintreda.common.mybatis.entity.SysRole;
import com.kintreda.common.mybatis.entity.SysUser;
import com.kintreda.common.mybatis.service.ISysAdminService;
import com.kintreda.common.mybatis.service.ISysRoleService;
import com.kintreda.common.mybatis.service.ISysUserService;
import com.kintreda.common.oauth.security.entity.TokenRole;
import com.kintreda.common.oauth.security.entity.TokenUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jane
 * Date: 2020/1/2
 * Time: 7:43 下午
 * Description:
 * import com.initialize.service.api.system.feign.IUserClient;
 */
@Slf4j
@Service("securityUserService")
public class UserService implements UserDetailsService {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ISysAdminService iSysAdminService;
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysUserService iSysUserService;


    @Override
    public UserDetails loadUserByUsername(String string) throws UsernameNotFoundException {
        // 拆分用户类型
        String[] split = string.split(":");
        String userType = split[0];
        String userId = split[1];
        //权限集合
        List<TokenRole> roleList = new ArrayList<>();
        //后台用户
        if (userType.equals(UserTypeEnum.后台管理员.getType())){
            SysAdmin admin = getCurrentUser(userType, userId, SysAdmin.class);
            roleList = getRoles(admin.getRoleId());
            return TokenUser.builder()
                    .userId(admin.getAdmId())
                    .userType(userType)
                    .nickName(admin.getName())
                    .username(admin.getUsername())
                    .password(admin.getPassword())
                    .roles(roleList)
                    .build();
        }
        //前端用户
        if (userType.equals(UserTypeEnum.用户.getType())){
            SysUser user = getCurrentUser(userType, userId, SysUser.class);
            roleList = getRoles(user.getRoleId());
            return TokenUser.builder()
                    .userId(user.getUserId())
                    .userType(userType)
                    .nickName(user.getNickName())
                    .username(user.getNickName())
                    .roles(roleList)
                    .build();
        }
        //其他
        return null;
    }


    /**
     * 普通用户
     * @param userType
     * @param userId
     * @return
     */
    public  <T> T getCurrentUser(String userType, String userId,Class<T> clazz) {
        T result = null;
        if (userType.equals(UserTypeEnum.后台管理员.getType())){
            result = (T) iSysAdminService.getById(userId);
        }
        if (userType.equals(UserTypeEnum.用户.getType())){
            result = (T) iSysUserService.getById(userId);
        }
        return result;
    }

    /**
     * 普通用户
     * @param userType
     * @param userId
     * @return
     */
    public  <T> T getUser(String userType, String userId,Class<T> clazz) {
        String redisResult = redisUtils.get(RedisConstant.TOKEN+userType+":"+userId);
        SysUser user = null;
        if (StringUtils.isBlank(redisResult)){
            user = getCurrentUser(userType,userId,SysUser.class);
        }else{
            user = redisUtils.get(RedisConstant.TOKEN+userType+":"+userId,SysUser.class);
        }
        if (user == null) {
            return null;
        }else{
            redisUtils.set(RedisConstant.TOKEN+userType+":"+userId,user, 3600);
        }
        String s = JSONObject.toJSONString(user);
        return JSONObject.parseObject(s,clazz);
    }

    /**
     * 平台管理员
     * @param userType
     * @param userId
     * @return
     */
    public <T> T getAdmin(String userType,String userId,Class<T> clazz) {
        String redisResult = redisUtils.get(RedisConstant.TOKEN+userType+":"+userId);
        SysAdmin admin = null;
        if (StringUtils.isBlank(redisResult)){
            admin = getCurrentUser(userType,userId,SysAdmin.class);
        }else{
            admin = redisUtils.get(RedisConstant.TOKEN+userType+":"+userId,SysAdmin.class);
        }
        if (admin == null) {
            return null;
        }else{
            redisUtils.set(RedisConstant.TOKEN+userType+":"+userId,admin, 3600);
        }
        String s = JSONObject.toJSONString(admin);
        return JSONObject.parseObject(s,clazz);
    }


    /**
     * 获取角色权限
     * @param roleId
     * @return
     */
    private List<TokenRole> getRoles(Integer roleId) {
        SysRole sysRole = iSysRoleService.getById(roleId);
        //获取权限
        List<TokenRole> roleList = new ArrayList<>();
        TokenRole tokenRole = new TokenRole();
        tokenRole.setRoleId(sysRole.getRoleId());
        tokenRole.setName(sysRole.getName());
        tokenRole.setStatus(sysRole.getStatus());
        roleList.add(tokenRole);
        return roleList;
    }


    /**
     * 获取用户信息
     * @param userType
     * @param userId
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T userInfo(String userType,String userId,Class<T> clazz){
        T result = null;
        if (userType.equals(UserTypeEnum.后台管理员.getType())){
            result = (T) iSysAdminService.getById(userId);
        }
        if (userType.equals(UserTypeEnum.用户.getType())){
            result = (T) iSysUserService.getByUserId(userId);
        }
        return result;
    }
}
